import React, { Component } from 'react';
import { Icon, Dropdown, Menu, Popover, Popconfirm, message } from 'antd';
import { operateDevice } from '@api/update';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import runningImg from '../../../images/running.png';
import stopImg from '../../../images/stop.png';
import RefreshImg from '../../../images/refresh.svg';
import MyECharts from '@components/my-echarts';
import { NODE_NAME } from '@util/constants';
import _ from 'lodash';
import './index.less';

const prefixCls = 'node-card';

class NodeCard extends Component {
  constructor(props) {
    super(props);
  }
  getOption = (date, value) => {
    const option = {
      grid: {
        show: true,
        top: 2,
        left: 0,
        bottom: 0,
        width: '100%',
        height: '90%',
        backgroundColor: '#F7F9FC',
        borderWidth: 0
      },
      xAxis: {
        show: false,
        data: date
      },
      yAxis: {
        show: false
      },
      visualMap: {
        show: false,
        type: 'continuous',
        min: 75,
        max: value.max,
        inRange: { color: ['#ADBCCC', '#FF0000'] }
      },
      series: {
        symbol: 'none',
        type: 'line',
        lineStyle: {
          width: 1
        },
        data: value.data
      }
    };
    return option;
  };

  jumpToDetail = ip => {
    let ipStr = ip.replace(/\./g, '-') || '-';
    this.props.history.push(`/system-config/node-manage/node-detail/${ipStr}`);
  };

  operateDevice = (action, desc) => {
    const { ip, onOperate } = this.props;
    if (!ip) {
      return;
    }
    let actionCN = action === 'reboot' ? '重启' : '关机';
    let body = {
      action,
      actionCN,
      target: ip
    };
    operateDevice(body)
      .then(res => {
        if (_.get(res, 'data.data.status') === 'success') {
          message.success(`设备开始${desc}`);
          setTimeout(onOperate(), 5000);
        } else {
          message.error(`设备${desc}失败`);
        }
      })
      .catch(err => {
        const status = _.get(err, 'error.response.status');
        // 关机重启设备后服务会断掉，乐观认为操作成功
        if (status >= 500) {
          message.success(`设备开始${desc}`);
        } else {
          message.error(`设备${desc}失败`);
        }
      });
  };
  render() {
    const { data = [], ip, deviceStatus } = this.props;
    const latestData = _.last(data);
    const type = _.get(latestData, 'type');
    const status = _.get(_.find(deviceStatus, i => i.host === ip), 'device_id', false);
    const updated = _.get(latestData, 'created', '-');
    const date = [];
    const cpuData = [];
    const memoryData = [];
    const diskData = [];
    const netSendData = [];
    const netReciveData = [];
    const processData = [];
    data.forEach(item => {
      const time = _.get(item, 'created');
      const cpu = _.get(item, 'cpu');
      const memory = _.get(item, 'memory');
      const disk = _.get(item, 'disk');
      const netSend = _.get(item, 'netSend');
      const netRecive = _.get(item, 'netRecive');
      const processes = _.get(item, 'process');
      date.push(time);
      cpuData.push(cpu);
      memoryData.push(memory);
      diskData.push(disk);
      netSendData.push(netSend);
      netReciveData.push(netRecive);
      processData.push(processes);
    });
    const chartData = [
      {
        name: 'CPU 使用率',
        value: _.get(latestData, 'cpu', '-'),
        key: 'cpu',
        data: cpuData,
        max: 100,
        unit: '%'
      },
      {
        name: '内存使用率',
        value: _.get(latestData, 'memory', '-'),
        key: 'memory',
        data: memoryData,
        max: 100,
        unit: '%'
      },
      {
        name: '硬盘使用率',
        value: _.get(latestData, 'disk', '-'),
        key: 'disk',
        data: diskData,
        max: 100,
        unit: '%'
      },
      {
        name: '进程数',
        value: _.get(latestData, 'process', '-'),
        key: 'process',
        data: processData,
        max: 99999,
        unit: '个'
      },
      {
        name: '发送流量',
        value: _.get(latestData, 'netSend', '-'),
        key: 'netSend',
        data: netSendData,
        max: 99999,
        unit: 'kb/s'
      },
      {
        name: '接收流量',
        value: _.get(latestData, 'netRecive', '-'),
        key: 'netRecive',
        data: netReciveData,
        max: 99999,
        unit: 'kb/s'
      }
    ];

    const menu = (
      <Menu>
        <Menu.Item key="poweroff">
          <Popconfirm
            title={'确认关机？关机后将不能访问系统，执行中的任务将受到影响'}
            onConfirm={() => this.operateDevice('poweroff', '关机')}
          >
            <Icon type="poweroff" />
            &nbsp;关机
          </Popconfirm>
        </Menu.Item>
        <Menu.Item key="reboot">
          <Popconfirm
            title={'确认重启？重启过程中将不能访问系统，执行中的任务将受到影响'}
            onConfirm={() => this.operateDevice('reboot', '重启')}
          >
            <Icon type="redo" style={{ transform: 'rotateZ(-90deg)' }} />
            &nbsp;重启
          </Popconfirm>
        </Menu.Item>
      </Menu>
    );
    return (
      <div className={`${prefixCls} ${status ? '' : 'unactive'}`}>
        <div className={`${prefixCls}-header ${type}`}>
          <div>
            <div style={{ color: '#1E1F23' }}>{ip}</div>
            <span>{NODE_NAME[type] || ''}</span>
          </div>
          <Popover content={status ? '运行中' : '无法连接'}>
            <div className={`${prefixCls}-status ${status ? 'running' : ''}`}>
              <img src={status ? runningImg : stopImg} width="24px" />
            </div>
          </Popover>
        </div>
        <div className={`${prefixCls}-content`}>
          {chartData.map(item => {
            return (
              <div className={`${prefixCls}-content-item`} key={item.key}>
                <div className={`${prefixCls}-content-item-title`}>
                  <div>{item.name}</div>
                  <div className={`${item.key} ${item.value > 80 ? 'red' : ''}`}>
                    {item.value}
                    {item.unit}
                  </div>
                </div>
                <div className={`${prefixCls}-content-item-chart`}>
                  <MyECharts option={this.getOption(date, item)} />
                </div>
              </div>
            );
          })}
        </div>
        <div className={`${prefixCls}-footer`}>
          <div className={`${prefixCls}-footer-message`}>
            <img src={RefreshImg} style={{ width: 16, margin: '-4px 4px 0 0' }} />
            <span>最近更新：{updated}</span>
            <span
              className={`${prefixCls}-footer-message-link`}
              onClick={() => this.jumpToDetail(ip)}
            >
              查看详情
            </span>
          </div>
          <div className={`${prefixCls}-footer-operate`}>
            <Dropdown overlay={menu} placement="topCenter" trigger={['click']}>
              <Icon type="menu" style={{ cursor: 'pointer' }} />
            </Dropdown>
          </div>
        </div>
      </div>
    );
  }
}

NodeCard.propTypes = {
  data: PropTypes.array,
  history: PropTypes.object,
  ip: PropTypes.string,
  onOperate: PropTypes.func,
  deviceStatus: PropTypes.array
};

export default withRouter(NodeCard);
